<?php

class Core_View_Helper_Results extends Zend_View_Helper_Abstract
{

	private $_fields = array();
	private $_message = 'MSG_';
	private $_values = array();

	public function results($form, $keys, $values, $order, $url)
	{
		$this->generateFields($keys);
		$this->checkFields($values);
		$this->_values = $values;
		$str_keyword = $this->view->translate('keyword');

		foreach ($this->_fields as $key => $field)
		{
			if ($field == true)
			{
				$this->_message .= $key . '_';
				if (in_array($key, array('category', 'status')))
				{
					$path = $this->_values[$key];
					$this->_values[$key] = $form->$key->getMultiOption($path);
					if (empty($this->_values[$key]) && $key == 'category')
					{
						$path = trim($path, '%');
						$this->_values[$key] = Core_Model_DbTable_Category_Customs::getInstance()->getCategoryByPath($path)->name;
					}
				}
			}
		}
		
		$this->_message = trim($this->_message, '_');

		if ($this->_values['item_count'] > 1)
		{
			$this->_message .='_S';
		}
        $this->_values['url'] = $url;
		$this->_values = $this->sort($this->_values, $order);
		
		if (isset($this->_values['keyword']))
		{
			if ($this->_values['keyword'] == $str_keyword || trim($this->_values['keyword'])=='')
			{
				unset($this->_values['keyword']);
			}
		}      
		return vsprintf($this->view->translate(strtoupper($this->_message)), $this->_values);
	}

	private function sort($values, $orders)
	{
		$temp = array();

		foreach ($orders as $order)
		{
			if (key_exists($order, $values))
			{
				if (!empty($values[$order]) || $order == 'item_count')
				{
					$temp[$order] = $this->view->escape($values[$order]);
				}
			}
		}
		return $temp;
	}

	private function checkFields($values)
	{
		$str_keyword = $this->view->translate('keyword');

		foreach ($this->_fields as $key => $value)
		{
			if ($key != 'keyword')
			{
				if (!empty($values[$key]))
				{
					$this->_fields[$key] = true;
				}
			}
			else
			{
				if (isset($values[$key]))
				{
					if (trim($values[$key]) != $str_keyword && trim($values[$key]) != '')
					{
						$this->_fields[$key] = true;
					}
				}
			}
		}
	}

	private function generateFields($keys)
	{
		foreach ($keys as $key)
		{
			$this->_fields[$key] = false;
		}
	}

}